package tool

import (
	"net/http"
	"time"
	"adai.design/homeserver/log"
	"strings"
)

var router = map[string]http.Handler{}

type routerHTTP struct {}

func (*routerHTTP) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	request.ParseForm()

	path := strings.Split(request.URL.Path, "/")
	if h, ok := router[path[1]]; ok {
		h.ServeHTTP(response, request)
		return
	}

	http.Error(response, "404 not found", 404)
}

func Start(end chan bool) {
	go func() {
		serveHTTP := http.Server{
			Addr: ":8080",
			Handler: &routerHTTP{},
			ReadTimeout: 5 * time.Second,
		}

		err := serveHTTP.ListenAndServe()
		if err != nil {
			log.Error("listen and serve: %s", err)
		}
		end <- true
	}()
}
